'use strict'

define([ 'jquery', 'bootstrap', 'select2', 'bodyform', 'shiftform', 'validate',
    'validate.en'], function($) {
  return {
    init : function() {
      this.initPage();
      this.initSelect2();
      this.scoreSelect2();
      this.initChoice(); 
      this.initShowDetail();
      this.initHideTextarea();
      this.submitScore();
      this.stengthData = this._generateSelectData("strong");
      this.dnData = this._generateSelectData("weak");
    },
    
    initPage : function() {
//      $(".autosize-textarea").autosize();
    },
    
    initSelect2: function() {
      var that = this;
      
      $('select.select2').select2({
        theme : "classic",
        placeholder : $(this).data("placeholder"),
        minimumResultsForSearch : -1,
        allowClear : true,
      }).on('change', function() {
        if(this.value) {
          var name = $(this).attr('name');
          var comment = $('textarea[name="'+ name + 'Comment"]').val();
          var select2Data = name.indexOf("strength") >= 0 ? that._calculateSelect2(that.stengthData, $(this).find(":selected").data("name")) : that._calculateSelect2(that.dnData, $(this).find(":selected").data("name"))
          $(this).parent().next().find("input[name='choose']").val(this.value);
          if(this.value != 'OTHER') {
        	  $('input[name="'+ name + 'Title"]').select2({
                  placeholder : $(this).data("placeholder"),
                  minimumResultsForSearch : -1,
                  allowClear : true,
                  data: function() { return {results: select2Data}; }
                }).unbind('change').on('change', function(){
                  if(this.value == 'other') {
//                    $(this).after('<input type="text" name="'+name+'Other" data-validate="required" class="form-control" style="margin-top: 10px;" placeholder="other title" />');
                    that.submitScore();
//                    $('textarea[name="'+ name + 'Comment"]').val('');
                  } else {
//                    $('input[name="'+name+'Other"]').remove();
                	  if(!comment) {
                		  $('textarea[name="'+ name + 'Comment"]').val(that._generateTextarea(name));
                	  }
                  }
                  $(this).select2('destroy');
                  that.editSelect2(this);
                });
          } else {
        	  var titlePlaceholder = $('input[name="'+ name + 'Title"]').data("placeholder");
        	  $('input[name="'+ name + 'Title"]').val("").attr("placeholder", titlePlaceholder);
        	  $('input[name="'+ name + 'Title"]').select2('destroy');
          }
          if(!comment) {
        	  $('textarea[name="'+ name + 'Comment"]').val(that._generateTextarea(name));
          }
          $('input[name="'+ name + 'Title"]').select2('val', '').removeClass("hide");
        } else {
//          $('textarea[name="'+ name + 'Comment"]').val('');
//          $('textarea[name="'+ name + 'Other"]').remove();
          $('input[name="'+ name + 'Title"]').select2('val', '').addClass("hide");
        }
      });
      
    },
    
    editSelect2: function(el) {
      var that = this;
      $(el).on("change", function(e){
        if($(this).val() == '') {
          var $select2 = $(this).prev();
          var name = $($select2).attr('name');
          var comment = $('textarea[name="'+ name + 'Comment"]').val();
          var select2Data = name.indexOf("strength") >= 0 ? that._calculateSelect2(that.stengthData, $($select2).find(":selected").data("name")) : that._calculateSelect2(that.dnData, $($select2).find(":selected").data("name"));
          $($select2).parent().next().find("input[name='choose']").val($select2.val());
          $('input[name="'+ name + 'Title"]').select2({
            placeholder : $(this).data("placeholder"),
            minimumResultsForSearch : -1,
            allowClear : true,
            data: function() { return {results: select2Data}; }
          }).unbind('change').on('change', function(){
            if(this.value == 'other') {
//              $(this).after('<input type="text" name="'+name+'Other" class="form-control" style="margin-top: 10px;" placeholder="other title" />');
//              $('textarea[name="'+ name + 'Comment"]').val('');
            } else {
//              $('input[name="'+name+'Other"]').remove();
            	if(!comment) {
            		$('textarea[name="'+ name + 'Comment"]').val(that._generateTextarea(name));
            	}
            }
            $(this).select2('destroy');
            that.editSelect2(this);
          });
        }
      })
    },
    
    scoreSelect2: function() {
      $("select[name='score']").on("change", function() {
        if($("select[name='score']").val()) {
          $(".visibility").css("visibility", "visible")
        } else {
          $(".visibility").css("visibility", "hidden")
        }
      })
      
    },
    
    _generateSelectData : function(classes) {
      var data = {};
      $(".messages").find("div."+classes).each(function(){
        var key = $(this).data("com");
        var values = [];
        $(this).find("div.anchor").each(function(){
          var anchorJson = {};
          $(this).find("input").each(function() {
            anchorJson[$(this).attr("name")] = $(this).val();
          })
          values.push(anchorJson);
        })
        data[key] = values;
      })
      return data;
    },
    
    _calculateSelect2(data, key) {
      var arrays = data[key];
      var result = [];
      for(var item in arrays) {
        var value = {};
        value['id']=arrays[item].name;
        value['text']=arrays[item].name;
        result.push(value)
      }
      result.push({'id': 'other', 'text': 'other'})
      return result;
    },
    
    _generateTextarea(name) {
      var key = $("select[name='"+name+"'] option:checked").data("name");
      var text = name.indexOf("strength") >= 0 ? $("div.strong[data-com='"+key+"']").data("effective") : $("div.weak[data-com='"+key+"']").data("ineffective"); 
      console.log(text);
      return text;
    },
    
    initChoice: function() {
      $(document).on("click", ".recommendation input[type='checkbox']", function() {
        if(!$(this).prop("checked")) {
        	$(this).parents("tr").find("input[type='checkbox']").prop("disabled", false)
        } else {
          $(this).parents("tr").find("input[type='checkbox']").prop("disabled", true)
          $(this).prop("disabled", false)
        }
      })
    },
    
    initShowDetail: function() {
      $(document).on('click', '.anchor-link', function(e) {
        var currentIndex = $(e.currentTarget).data("option");
        $(".scoring-details").eq(currentIndex).show().siblings().hide();
      })
      
      $(document).on('click', '.close-details', function(e) {
        $(".scoring-details").hide();
      })
    },
    
    initHideTextarea: function() {
      
      $('[data-toggle="popover"]').popover({
        trigger: "manual"
      })
      
      $("input[name='choose']").each(function() {
        if(!$(this).prop("checked")) {
          $(this).parents(".col-xs-6").find("[name='chooseComment']").hide();
        } else {
          $(this).parents(".col-xs-6").find("[name='chooseComment']").show();
        }
      })
      
      $(document).on("change", "input[name='choose']", function() {
        var strengthLength = $("input[data-choose='strength']:checked").length;
        var developmentLength = $("input[data-choose='development']:checked").length;
       
        if($(this).prop("checked")) {
          if($(this).data("choose") =="strength" && strengthLength > 1) {
            $(this).parent("label").popover("show");
            $(this).prop({"checked": false})
            $(this).parents(".col-xs-6").find("[name='chooseComment']").hide();
          } else if($(this).data("choose") =="development" && developmentLength > 2) {
            $(this).prop({"checked": false})
            $(this).parent("label").popover("show");
            $(this).parents(".col-xs-6").find("[name='chooseComment']").hide();
          } else {
            $(this).parents(".col-xs-6").find("[name='chooseComment']").show();
          }
          
        } else {
          $(this).parents(".col-xs-6").find("[name='chooseComment']").val("").hide();
        }
      })
      
      $(document).on("mouseout", "input[name='choose']", function() {
        $('[data-toggle="popover"]').popover('hide')
      })
      
      
    },
    
    validateForm: function() {
      var strengthVal = $("input[data-choose='strength']:checked").parents(".col-xs-6").find("[name='chooseComment']").val();
      
      if(!strengthVal) {
        $(".validate-modal").modal('show')
        setTimeout(function() {
          $(".validate-modal").modal('hide')
        },1000)
        return false;
      }
       
      $("input[data-choose='development']:checked").each(function() {
        if(!$(this).parents(".col-xs-6").find("[name='chooseComment']").val().trim()) {
          $(".validate-modal").modal('show');
          setTimeout(function() {
            (".validate-modal").modal('hide')
          },1000)
          return false;
        }
      })
      
      var strengthLength = $("input[data-choose='strength']:checked").length;
      if (strengthLength != 1) {
        $(".validate-modal").modal('show');
        setTimeout(function() {
          (".validate-modal").modal('hide')
        },1000)
        return false;
      }
      
      var developmentLength = $("input[data-choose='development']:checked").length;
      if (developmentLength != 2) {
        $(".validate-modal").modal('show');
        setTimeout(function() {
          (".validate-modal").modal('hide')
        },1000)
        return false;
      }
      
      return true
    },
    
    submitScore: function() {
      var that = this;
      var $form = $('form[data-validate="true"]')
      $form.find("button[type='submit']").unbind("click");
      $form.bt_validate()  //bind validate
      $form.bodyform({
        beforeSubmit : function(el) {
          var result = true;
          $form.trigger("validate.ajax.submit");
          result = $.bt_validate.result[$.bt_validate.form_id];
          if(!result) {
            return result;
          }
          if($form.data("type") != 'choose') {
            result = that.validateForm()
          }

          return result;
        }
      })
    }
  }
})
